const express = require('express');
const router = express.Router();
const { User } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound, BadRequest, Unauthorized } = require('http-errors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { Op } = require('sequelize');
const validateCaptcha = require('../middlewares/validate-captcha');
const { delKey } = require('../utils/redis');
// const sendMail = require('../utils/mail')
const { mailProducer } = require('../utils/rabbit-mq');
/**
 * 用户注册
 *
 * POST /auth/sign_up
 * **/
router.post('/sign_up', validateCaptcha, async function (req, res) {
  try {
    const body = {
      email: req.body.email,
      username: req.body.username,
      nickname: req.body.nickname,
      password: req.body.password,
      sex: 2,
      role: 0,
    };
    const user = await User.create(body);
    delete user.dataValues.password;
    await delKey(req.body.captchaKey);

    // 替换为美观的邮件模板（注意传入user.nickname）
    const html = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册成功通知</title>
    <style>
        body { margin: 0; padding: 0; background-color: #f5f7fa; font-family: "Microsoft YaHei", Arial, sans-serif; }
        .container { max-width: 600px; margin: 30px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); overflow: hidden; }
        .header { padding: 20px; background-color: #2c3e50; text-align: center; }
        .header h1 { margin: 0; color: #ffffff; font-size: 20px; font-weight: 500; }
        .content { padding: 30px 20px; line-height: 1.8; color: #333333; }
        .content .greeting { font-size: 16px; margin-bottom: 20px; }
        .content .greeting span { color: #e74c3c; font-weight: bold; }
        .content .info { margin: 20px 0; padding: 15px; background-color: #f8f9fa; border-left: 4px solid #3498db; border-radius: 4px; }
        .divider { margin: 25px 0; height: 1px; background-color: #eeeeee; }
        .footer { padding: 20px; text-align: center; font-size: 12px; color: #999999; background-color: #f8f9fa; }
        .footer p { margin: 5px 0; }
        @media (max-width: 600px) {
            .container { margin: 15px; }
            .content { padding: 20px 15px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>注册成功通知</h1>
        </div>
        <div class="content">
            <div class="greeting">
                您好，<span>${user.nickname}</span>
            </div>
            <p>恭喜您成功注册成为我们的会员！</p>
            <div class="info">
                您可以立即登录账号，体验我们的全部服务~
            </div>
            <div class="divider"></div>
            <p>若您有任何问题，欢迎随时联系我们的客服团队。</p>
        </div>
        <div class="footer">
            <p>© 2025 您的平台名称 版权所有</p>
            <p>此邮件为系统自动发送，请勿直接回复</p>
        </div>
    </div>
</body>
</html>
        `;

    const msg = {
      to: user.email,
      subject: '注册通知',
      html,
    };

    // 调用sendMail时传入res（确保错误能返回给前端）
    // await sendMail(user.email, '注册通知', html, res);
    // 改用消息队列RabbitMq
    await mailProducer(msg);
    success(res, '创建用户成功', { user }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 用户登录
 *
 * POST /auth/sign_in
 * */

router.post('/sign_in', async function (req, res) {
  try {
    const { login, password } = req.body;
    // console.log(req.body,'999999', crypto.randomBytes(32).toString('hex'))
    if (!login) {
      throw new BadRequest('邮箱用户名必须填写');
    }
    if (!password) {
      throw new BadRequest('密码必须填写');
    }
    const condition = {
      where: {
        [Op.or]: [{ email: login }, { username: login }],
      },
    };

    const user = await User.findOne(condition);
    if (!user) {
      throw new NotFound('用户不存在');
    }
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new Unauthorized('密码错误');
    }
    // if (user.role !== 0) {
    //     throw new Unauthorized('没有登录权限')
    // }
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: '24h' }
    );
    success(res, '登录成功', { token });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
